

from django.db.models import F
from django.urls import reverse
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import loader
from django.utils import timezone
from django.views import generic
from .models import Question, Choice, User

def test(request):
    return render(request, "myApp/base.html")
def login(request):
    return render(request, "myApp/login.html")
def logout(request):
    request.session.flush()
    return render(request,"myApp/login.html")


def index(request):
    global context, user,template
    try:
        uid = request.POST['uid']
        password = request.POST['password']
        request.session['uid_s']=uid


        try:
            user=User.objects.get(uid=uid)
            if user.password != password:
                template = loader.get_template('myApp/login.html')
                context = {'message': '密码错误'}
                return HttpResponse(template.render(context, request))

        except:
            template = loader.get_template('myApp/login.html')
            context = {'message': '请输入正确的账号！'}
            return HttpResponse(template.render(context, request))
        else:
            latest_question_list = Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:8]
            context = {
                'latest_question_list': latest_question_list,
                'user':user
            }
            template = loader.get_template('myApp/index.html')
            return HttpResponse(template.render(context, request))
    except(KeyError,):
        try:
            if request.session['uid_s']:
                latest_question_list = Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:8]
                context = {
                    'latest_question_list': latest_question_list,
                    'user': user
                }
                template = loader.get_template('myApp/index.html')
            else:
                template = loader.get_template('myApp/login.html')
                context = {'message': '请输入正确的账号密码！'}

            return HttpResponse(template.render(context, request))
        except:
            return render(request, "myApp/login.html")



# class IndexView(generic.ListView):
#     template_name = 'myApp/index.html'
#     context_object_name = 'latest_question_list'
#
#     def get_queryset(self):
#     #     return Question.objects.order_by('-pub_date')[:5]
#         return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]


# class MyView(generic.ListView):
#     user=User.objects.get()
#     template_name = 'myApp/myvote.html'
#     context_object_name = 'my_question_list'
#
#     def get_queryset(self):
#         return Question.objects.filter(choice__user=)
def myView(request,uid):
    user=User.objects.get(uid=uid)
    choice=user.choice.filter(user__choice=user.uid)

    return render(request, 'myApp/myvote.html', {'my_question_list': choice,'user':user})




def detail(request, question_id):
    try:
        user=User.objects.get(uid=request.session['uid_s'])
        question = Question.objects.filter(pub_date__lte=timezone.now()).get(id=question_id)
        latest_question_list = Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:8]
    except Question.DoesNotExist:
        raise Http404("问题不存在")
    return render(request, 'myApp/detail.html', {'question': question,'user':user,'latest_question_list':latest_question_list})
# class DetailView(generic.DetailView):
#
#     model = Question
#
#     # template_name = 'myApp/detail.html'
#     def get_queryset(self):
#         return Question.objects.filter(pub_date__lte=timezone.now())




def results(request, question_id):
    question=get_object_or_404(Question,pk=question_id)
    user = User.objects.get(uid=request.session["uid_s"])
    latest_question_list = Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:8]
    return render(request,'myapp/results.html',{'question':question,'user':user,'latest_question_list':latest_question_list})
# class ResultsView(generic.DetailView):
#     model = Question
    # (template_name = 'myApp/results.html')


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    user = User.objects.get(uid=request.session["uid_s"])
    latest_question_list = Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:8]
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):

        return render(request, 'myApp/detail.html', {
            'question': question,
            'error_message': "你当前未选择！",
            'user':user,
            'latest_question_list':latest_question_list
        })
    else:
        question=Question.objects.get(id=question_id)
        user=User.objects.get(uid=request.session["uid_s"])
        try:
            if user.choice.get(question__choice=selected_choice):
                return render(request, 'myApp/detail.html', {
                    'question': question,
                    'error_message': "你已参与过此投票！",
                    'user':user,
                    'latest_question_list':latest_question_list
                })
        except:
            selected_choice.votes = F('votes') + 1
            user.choice.add(selected_choice)
            user.save()
            selected_choice.save()

        return HttpResponseRedirect(reverse('myApp:results', args=(question.id,)))





def search(request):
    key=request.GET['key']
    print(key)
    search_question_list=Question.objects.filter(question_text__icontains=key)
    return render(request,'myApp/search.html',{'search_question_list':search_question_list})
# class Search(generic.ListView):
#     template_name = 'myApp/search.html'
#     context_object_name = 'search_question_list'
#
#
#     def get_queryset(self):
#         return Question.objects.filter(question_text__icontains='牛')
